class FirstComponent extends HTMLElement {
  constructor() {
    super();
    console.log('constructor');
  }
  data = {
    count: 0,
  };
  add() {
    this.data.count += 1;
    this.querySelector('#count').innerHTML = this.data.count;
    console.log('add', this.data.count);
  }
  sub() {
    this.data.count -= 1;
    this.querySelector('#count').innerHTML = this.data.count;
    console.log('sub', this.data.count);
  }
  getTemplate() {
    const template = `
      <main style="display: flex;">
        <button id="sub">减</button>
        <div id="count" style="color: red;padding: 0 10px;text-align: center;">
          ${this.innerHTML || this.data.count}</div>
        <button id="add">加</button>
      </main>
    `;
    console.log('getTemplate', template.trim());
    return template.trim();
  }
  render() {
    this.innerHTML = this.getTemplate();
    this.querySelector('#add').onclick = () => this.add();
    this.querySelector('#sub').onclick = () => this.sub();
  }
  connectedCallback() {
    // 在元素被添加到文档之后，浏览器会调用这个方法
    //（如果一个元素被反复添加到文档／移除文档，那么这个方法会被多次调用）
    console.log(
      'connectedCallback',
      '在元素被添加到文档之后，浏览器会调用这个方法',
      this,
    );
    this.render();
  }
}
window.customElements.define('first-component', FirstComponent);
